package com.loren.demo32.tenant;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
public class TenantRoutingDataSource extends AbstractRoutingDataSource {

    private final CustomTenantResolver customTenantResolver;

    public TenantRoutingDataSource(CustomTenantResolver customTenantResolver) {
        this.customTenantResolver = customTenantResolver;
        this.setDefaultTargetDataSource(createDatabase("multi_00"));
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("multi_01", createDatabase("multi_01"));
        targetDataSources.put("multi_02", createDatabase("multi_02"));
        setTargetDataSources(targetDataSources);
    }

    @Override
    protected String determineCurrentLookupKey() {
        return customTenantResolver.resolveCurrentTenantIdentifier();
    }

    private DataSource createDatabase(String database) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://172.28.128.100:3306/" + database + "?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }
}
